<?php
namespace app\api\controller;

use app\BaseController;
use app\common\model\mysql\YwBgConfig as models;
use app\common\model\mysql\CommonSysCarousel;
use app\common\model\mysql\YwCountdowmConfig;
use app\common\model\mysql\YwCountdowmRecord;
use app\common\model\mysql\YwCoupon;
use app\common\model\mysql\YwCouponReceiveRecord;
use app\common\model\mysql\CommonUser;
use app\common\model\mysql\CommonSysOtherConfig;
use app\common\model\mysql\YwPlatform;
use app\common\model\mysql\CommonPayPresentOrder;
use app\common\model\mysql\CommonPayPriceChangeRecord;
use app\common\model\mysql\YwProductType;
use app\common\model\mysql\CommonPayRechargeOrder;
use app\common\model\mysql\YwRollRecord;
use app\common\model\mysql\YwService;
use think\facade\Db;

class Home extends BaseController
{

    public function initialize()
    {
    }

    public function test(){
        echo getNewOrderNumber();
    }

    /*
     * 图片上传
     */
    public function uploadImageOss(){
        /*$file = $_FILES['file'];
        $name = $file['name'];
        $nameList = explode('.',$name);
        if(!in_array($nameList[1],['jpg','png','jpeg','gif'])) {
            jsonFail('请上传正确格式的图片');
        }
        $filename = generateStr(16).'.'.$nameList[1];
        $str = "uploads/file/" . $filename;
        if (file_exists($str)) {
            jsonFail('文件已存在');
        }else{
            move_uploaded_file($_FILES["file"]["tmp_name"],$str);
        }
        $wwwRoot = $_SERVER['DOCUMENT_ROOT'];
        require_once $_SERVER["DOCUMENT_ROOT"] . '/../extend/Oss.php';
        $oss = new \Oss();
        $res = $oss->uploadToOss($wwwRoot.'/'.$str,$filename);
        //删除上传到服务器的临时文件
        unlink($wwwRoot.'/'.$str);
        if($res == 'ok'){
            $data = [
                'src' => env('oss_path').$filename
            ];
            jsonSuccess($data);
        }else{
            jsonFail('上传失败');
        }*/
        $file = $_FILES['file'];
        $name = $file['name'];
        $nameList = explode('.',$name);
        if(!in_array($nameList[1],['jpg','png','jpeg','gif'])) {
            jsonFail('请上传正确格式的图片');
        }
        $filename = generateStr(16).'.'.$nameList[1];
        $str = "uploads/file/" . $filename;
        if (file_exists($str)) {
            jsonFail('文件已存在');
        }else{
            move_uploaded_file($_FILES["file"]["tmp_name"],$str);
        }
        $data = [
            'src' => fullurl($str)
        ];
        jsonSuccess($data);
    }


    /*
     * 加载背景图片
     */
    public function loadBg(){
        $model = models::where(['is_delete'=>0,'status'=>1])->field('image')
            ->order('order_num','desc')->find();
        $model['image'] = fullurl($model['image']);
        $data = [
            'model' => $model
        ];
        jsonSuccess($data);
    }

    /*
     * 平台列表
     */
    public function platformList(){
        $lists = YwPlatform::where(['is_delete'=>0,'status'=>1])->field('id,name,image')
            ->order('order_num','desc')->select();
        $data = [
            'lists' => $lists
        ];
        jsonSuccess($data);
    }

    /*
     * 产品分类列表
     */
    public function productTypeList(){
        $lists = YwProductType::where(['is_delete'=>0,'status'=>1])->field('id,name,image')
            ->order('order_num','desc')->select();
        $data = [
            'lists' => YwProductType::fillModelApis($lists)
        ];
        jsonSuccess($data);
    }

    /*
     * 加载倒计时等
     */
    public function homeCountDown(){
        $where = [];
        $where[] = ['start_time','<=',date('Y-m-d H:i:s')];
        $where[] = ['end_time','>',date('Y-m-d H:i:s')];
        $model = YwCountdowmRecord::where($where)->find();
        if(empty($model)){
            $model = YwCountdowmRecord::where('start_time','>',date('Y-m-d H:i:s'))->order('start_time','asc')->find();
            if(empty($model)){
                $data = [
                    'to_time' => time(),
                    'now_time' => time(),
                    'to_time_d' => date('Y-m-d H:i:s'),
                    'now_time_d' => date('Y-m-d H:i:s'),
                    'is_countdown' => 0,
                    'remark' => '没有倒计时活动',
                    'number' => ''
                ];
            }else{
                $data = [
                    'to_time' => strtotime($model['start_time']),
                    'now_time' => time(),
                    'to_time_d' => $model['start_time'],
                    'now_time_d' => date('Y-m-d H:i:s',time()),
                    'is_countdown' => 2,
                    'remark' => '开始倒计时',
                    'number' => $model['number']
                ];
            }
        }else{
            $data = [
                'to_time' => strtotime($model['end_time']),
                'now_time' => time(),
                'to_time_d' => $model['end_time'],
                'now_time_d' => date('Y-m-d H:i:s',time()),
                'is_countdown' => 3,
                'remark' => '结束倒计时',
                'number' => $model['number']
            ];
        }
        //$data = YwCountdowmConfig::getCountDown();
        jsonSuccess($data);
    }

    /*
     * 加载倒计时等
     */
    public function homeCountDown1(){
        $data = YwCountdowmConfig::getCountDown();
        jsonSuccess($data);
    }


    /*
     * 卡券列表
     */
    public function couponList(){
        $fildes = 'product_type_id,word,page';
        $receiveData = getData($this->request->post(),$fildes);
        $where = [];
        $where[] = ['is_delete','=',0];
        $where[] = ['status','=',1];
        if(!empty($receiveData['product_type_id'])){
            $where[] = ['product_type_id','=',$receiveData['product_type_id']];
        }
        if(!empty($receiveData['word'])){
            $where[] = ['product_name','like','%'.$receiveData['word'].'%'];
        }
        if(empty($receiveData['page'])){
            $receiveData['page'] = 1;
        }
        $limit_start = ($receiveData['page']-1) * env('page_size');
        $lists = YwCoupon::where($where)->field('id,product_name,product_price,discount_num,image,product_intro')
            ->order('order_num','desc')
            ->limit($limit_start,env('api_page_size'))->select();
        $data = [
            'lists' => YwCoupon::fillModelApis($lists),
            'is_load' => isLoad(count($lists),env('api_page_size'))
        ];
        jsonSuccess($data);
    }

    /*
     * 加载客服人员
     */
    public function loadService(){
        $model = YwService::where(['status'=>1,'is_delete'=>0])->order('create_time','desc')->find();
        $data = [
            'service_url' => empty($model) ? '' : $model['service_url']
        ];
        jsonSuccess($data);
    }

    /*
     * 获取滚动屏幕
     */
    public function getRollRecordList(){
        $lists = YwRollRecord::where(['is_delete'=>0,'status'=>1])->field('id,content')
            ->select();
        $data = [
            'lists' => $lists
        ];
        jsonSuccess($data);
    }

    /*
     * 轮播图
     */
    public function getCarouselList(){
        $lists = CommonSysCarousel::where(['is_delete'=>0,'status'=>1])->field('id,image')
            ->order('order_num','desc')->select();
        $data = [
            'lists' => CommonSysCarousel::fillModelApis($lists)
        ];
        jsonSuccess($data);
    }

    /*
     * 卡券详情
     */
    public function couponDetail(){
        $fildes = 'id';
        $receiveData = getData($this->request->post(),$fildes);
        $model = YwCoupon::where(['id'=>$receiveData['id'],'is_delete'=>0,'status'=>1])->find();
        if(empty($model)){
            jsonFail('卡券不存在');
        }
        $data = [
            'model' => YwCoupon::fillModelApi($model)
        ];
        jsonSuccess($data);
    }

    /*
     * 购买卡券
     */
    public function receiveCoupon(){
        $fildes = 'id,token';
        $receiveData = getData($this->request->post(),$fildes);
        //校验token
        $admin = CommonUser::checkToken($receiveData['token']);
        $coupon = YwCoupon::where(['id'=>$receiveData['id'],'is_delete'=>0,'status'=>1])->find();
        if(empty($coupon)){
            jsonFail('卡券不存在');
        }
        $result = YwCountdowmConfig::getCountDown();
        if($result['is_countdown'] != 3){
            jsonFail('当前时间暂不可抢券');
        }
        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['is_delete','=',0];
        $one = YwCountdowmConfig::where($where)->find();
        if(date('H:i:s') >= $one['end_time']){
            jsonFail('当前时间暂不可抢券');
        }
        if($coupon['number'] - $coupon['already_num'] <= 0){
            jsonFail('卡券数量不足');
        }
        if($admin['price'] < $coupon['product_price']){
            jsonFail('账户余额不足，不能购买该优惠券');
        }
        Db::startTrans();
        try{
            //YwCoupon::where(['id'=>$receiveData['id']])->lock(true)->update();
            $insertData = [
                'coupon_id' => $coupon['id'],
                'customer_id' => $admin['id'],
                'number' => 1,
                'order_number' => getNewOrderNumber(),
                'create_time' => date('Y-m-d H:i:s'),
                'buy_price' => YwCouponReceiveRecord::getBuyPrice($coupon)
            ];
            YwCouponReceiveRecord::insert($insertData);
            $lastId = YwCouponReceiveRecord::getLastInsID();

            $after_price = doubleval($admin['price']) - doubleval($coupon['product_price']);

            //购买优惠券后余额减少
            CommonPayPriceChangeRecord::insert([
                'customer_id' => $admin['id'],
                'price' => $coupon['product_price'],
                'before_price' => $admin['price'],
                'before_price' => $after_price,
                'type' => 8,
                'create_time' => date('Y-m-d H:i:s'),
                'source_id' => $lastId
            ]);

            CommonUser::where(['id'=>$admin['id']])->update([
                'price' => $after_price
            ]);

            YwCoupon::where(['id'=>$coupon['id']])->dec('already_num',1)->update();

            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            jsonFail(json_encode($e));
        }
        jsonSuccess([],'抢券成功');
    }

    /*
     * 提交充值订单
     */
    public function submitRechargeOrder(){
        $fildes = 'price,token,image_str,remark';
        $receiveData = getData($this->request->post(),$fildes);
        //校验token
        $admin = CommonUser::checkToken($receiveData['token']);
        if($receiveData['price'] <= 0){
            jsonFail('请输入正确的充值金额');
        }
        if(empty($receiveData['image_str'])){
            jsonFail('请上传充值凭证');
        }
        $insertData = [
            'customer_id' => $admin['id'],
            'price' => $receiveData['price'],
            'order_number' => getNewOrderNumber(),
            'image_str' => getImageListToStr1($receiveData['image_str']),
            'pay_type' => 3,
            'published_status' => 1,
            'create_time' => date('Y-m-d H:i:s')
        ];
        CommonPayRechargeOrder::insert($insertData);
        jsonSuccess();
    }

    /*
     * 提交提现
     */
    public function submitPresent(){
        $fildes = 'price,token,present_password';
        $receiveData = getData($this->request->post(),$fildes);
        //校验token
        $admin = CommonUser::checkToken($receiveData['token']);
        if($receiveData['price'] < 1000){
            jsonFail('提现金额不能低于1000元');
        }
        if($receiveData['price'] > 100000){
            jsonFail('提现金额不能超过100000元');
        }
        if($receiveData['price'] > $admin['price']){
            jsonFail('可提现余额不足，请重新输入');
        }
        if(empty($receiveData['present_password'])){
            jsonFail('请输入提现密码');
        }
        if(pwdMd5($receiveData['present_password']) != $admin['present_pwd']){
            jsonFail('提现密码不正确');
        }
        $otherconfig = CommonSysOtherConfig::where(['id'=>1])->find();
        Db::startTrans();
        try{
            $insertData = [
                'customer_id' => $admin['id'],
                'price' => $receiveData['price'],
                'create_time' => date('Y-m-d H:i:s'),
                'published_status' => 1,
                'fact_price' => getDecimalNum(doubleval($receiveData['price']) * (1000 - $otherconfig['present_percent']) / 1000),
                'order_number' => getNewOrderNumber(),
            ];
            CommonPayPresentOrder::insert($insertData);
            $lastId = CommonPayPresentOrder::getLastInsID();
            $after_price = doubleval($admin['price']) - doubleval($receiveData['price']);
            $data = [
                'customer_id' => $admin['id'],
                'price' => $receiveData['price'],
                'before_price' => $admin['price'],
                'after_price' => $after_price,
                'type' => 2,
                'create_time' => date('Y-m-d H:i:s'),
                'source_id' => $lastId
            ];
            CommonPayPriceChangeRecord::insert($data);
            CommonUser::where(['id'=>$admin['id']])->update(['price'=>$after_price]);

            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            jsonFail($e);
        }
        jsonSuccess();
    }

    /*
     * 提现记录
     */
    public function presentRecordList(){
        $fildes = 'token,page';
        $receiveData = getData($this->request->post(),$fildes);
        if(empty($receiveData['page'])){
            $receiveData['page'] = 1;
        }
        //校验token
        $admin = CommonUser::checkToken($receiveData['token']);
        $where = [];
        $where[] = ['customer_id','=',$admin['id']];
        $limit_start = ($receiveData['page']-1) * env('page_size');
        $lists = CommonPayPresentOrder::where($where)->order('id','desc')->limit($limit_start,env('api_page_size'))->select();
        $data = [
            'lists' => CommonPayPresentOrder::fillModels($lists),
            'is_load' => isLoad(count($lists),env('api_page_size'))
        ];
        jsonSuccess($data);
    }

    /*
     * 卡券购买记录
     */
    public function couponReceiveRecordList(){
        $fildes = 'token,page,status';//1待使用  2已使用 3已回购 4已过期
        $receiveData = getData($this->request->post(),$fildes);
        if(empty($receiveData['page'])){
            $receiveData['page'] = 1;
        }
        //校验token
        $admin = CommonUser::checkToken($receiveData['token']);
        $where = [];
        $where[] = ['customer_id','=',$admin['id']];
        if(!empty($receiveData['status'])){
            $where[] = ['status','=',$receiveData['status']];
        }
        $limit_start = ($receiveData['page']-1) * env('page_size');
        $lists = YwCouponReceiveRecord::where($where)->order('id','desc')->limit($limit_start,env('api_page_size'))->select();
        $data = [
            'lists' => YwCouponReceiveRecord::fillModels($lists),
            'is_load' => isLoad(count($lists),env('api_page_size'))
        ];
        jsonSuccess($data);
    }

    /*
     * 首页轮播购买记录
     */
    public function couponBoradList(){
        $lists = YwCouponReceiveRecord::field('*')->order('id','desc')
            ->limit(0,20)->select();
        $data = [
            'lists' => YwCouponReceiveRecord::fillModels($lists),
        ];
        jsonSuccess($data);
    }

}
